package jchat.genral;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	//private final WeakReference<ImageView> imageViewReference;
	 String filePath;
Context c;
	/*public ImageDownloaderTask(ImageView imageView) {
		imageViewReference = new WeakReference<ImageView>(imageView);
	}*/

	@Override
	// Actual download method, run in the task thread
	protected Bitmap doInBackground(String... params) {
		// params comes from the execute() call: params[0] is the url.
		return downloadBitmap(params[0]);
	}

	@Override
	// Once the image is downloaded, associates it to the imageView
	protected void onPostExecute(Bitmap bitmap) {
		
		if (isCancelled()) {
			bitmap = null;
			
		}
		super.onPostExecute(bitmap);
		 java.text.DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		   //get current date time with Date()
		   Date date = new Date();
		   System.out.println(dateFormat.format(date));
		   String temp_name=dateFormat.format(date);
		storeImage(bitmap,temp_name+".jpg" );
		/*if (imageViewReference != null) {
			ImageView imageView = imageViewReference.get();
			if (imageView != null) {

				if (bitmap != null) {
					//imageView.setImageBitmap(bitmap);
				//	String path=Environment.getExternalStorageDirectory().toString();
				//	File relocation=new File(path)
					//savePicture(bitmap,"my_image.jpg");
					  java.text.DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
					   //get current date time with Date()
					   Date date = new Date();
					   System.out.println(dateFormat.format(date));
					   String temp_name=dateFormat.format(date);
				//String path=	storeImage(bitmap,temp_name+".jpg");
					//storeImage
					
				} else {
					imageView.setImageDrawable(imageView.getContext().getResources()
							.getDrawable(R.drawable.blank));
				}
			}

		}*/
	}

	static Bitmap downloadBitmap(String url) {
		final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
		final HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode
						+ " while retrieving bitmap from " + url);
				return null;
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
					
					   final int THUMBSIZE = 64;

			            
					
					return bitmap;
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (Exception e) {
			// Could provide a more explicit error message for IOException or
			// IllegalStateException
			getRequest.abort();
			Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
		} finally {
			if (client != null) {
				client.close();
			}
		}
		return null;
	}
	
	public  String storeImage(Bitmap imageData, String filename) {
		//get path to external storage (SD card)
	    filePath = null ;
		String iconsStoragePath = Environment.getExternalStorageDirectory() + "/shyam/myImages/";
		File sdIconStorageDir = new File(iconsStoragePath);

		//create storage directories, if they don't exist
		sdIconStorageDir.mkdirs();

		try {
			filePath= sdIconStorageDir.toString() + filename;
			FileOutputStream fileOutputStream = new FileOutputStream(filePath);

			BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

			//choose another format if PNG doesn't suit you
			imageData.compress(CompressFormat.JPEG, 100, bos);

			bos.flush();
			bos.close();

		} catch (FileNotFoundException e) {
			Log.w("TAG", "Error saving image file: " + e.getMessage());
			
		} catch (IOException e) {
			Log.w("TAG", "Error saving image file: " + e.getMessage());
			
		}

		return filePath;
	}	
	public String getpath()
	{
		return filePath;
	}
	
	
	
	
	
}